<template>
  <el-menu
    :default-active="activeMenuItemRouteName"
    :mode="mode"
    :class="popperClass"
    :ellipsis="false"
    :collapse="mode === 'vertical' && collapse"
    :menu-trigger="menuTrigger"
    :unique-opened="true"
    @select="onSelect"
  >
    <LsyMenuItem
      v-for="item in menus"
      :key="item.index"
      :item="item"
      :level="0"
      :popper-class="popperClass"
    ></LsyMenuItem>
  </el-menu>
</template>

<script setup>
import { useRoute } from 'vue-router'
import { computed, watch } from 'vue'
import { ref } from 'vue'
import { toRefs } from 'vue'
import { reduceMenuArr } from './LsyMenuUtil'
import { nextTick } from 'vue'
import { useMediaQuery } from '@/hooks/MediaQueryHook'

defineOptions({ name: 'LsyMenu' })
const props = defineProps({
  menus: {
    type: Array,
    default: () => [],
  },
  mode: {
    type: String,
    default: 'horizontal',
  },
  popperClass: {
    type: String,
    default: undefined,
  },
  collapse: {
    type: Boolean,
    default: false,
  },
  customSetActiveIndex: {
    type: Boolean,
    default: false,
  },
  defaultActive: {
    type: String,
    default: undefined,
  },
})
const $emits = defineEmits(['onSelect'])
const $route = useRoute()
const { customSetActiveIndex, defaultActive, menus, mode } = toRefs(props)
const activeMenuItemRouteName = ref()
const supportHover = ref(false)
const menuTrigger = computed(() => {
  if (supportHover.value) {
    return mode.value === 'horizontal' ? 'hover' : 'click'
  } else {
    return 'click'
  }
})
useMediaQuery(
  'screen and (any-hover: hover)',
  () => {
    console.log('支持hover')
    supportHover.value = true
  },
  () => {
    console.log('不支持hover')
    supportHover.value = false
  }
)

const routeNameMapMenu = computed(() => {
  const map = new Map()
  reduceMenuArr(menus.value, map)
  return map
})

watch(
  [() => $route.name, defaultActive, routeNameMapMenu],
  ([newRouteName, newDefaultActive, newRouteNameMapMenu]) => {
    nextTick(() => {
      requestAnimationFrame(() => {
        updateActiveMenuItemRouteName(
          newRouteName,
          newDefaultActive,
          newRouteNameMapMenu
        )
      })
    })
  },
  { immediate: true }
)

function updateActiveMenuItemRouteName(
  newRouteName,
  newDefaultActive,
  newRouteNameMapMenu
) {
  if (!customSetActiveIndex.value) {
    let active = newRouteName
    const menuItem = newRouteNameMapMenu.get(active)
    if (menuItem) {
      if (menuItem.hide && menuItem.parentIndex) {
        active = menuItem.parentIndex
      }
    }
    activeMenuItemRouteName.value = active
  } else {
    console.log('newDefaultActive', newDefaultActive)
    activeMenuItemRouteName.value = newDefaultActive
  }
}

function onSelect(index, indexPath) {
  $emits('onSelect', index, indexPath)
}
</script>

<style scoped></style>
